package com.lineage.server.timecontroller.npc;

import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1MonsterInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.WorldMob;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NpcDigestItemTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(NpcDigestItemTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 5000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 5000L, 5000L);
  }
  
  public void run() {
    try {
      Collection<L1MonsterInstance> allMob = WorldMob.get().all();
      if (allMob.isEmpty())
        return; 
      Iterator<L1MonsterInstance> iter = allMob.iterator();
      while (iter.hasNext()) {
        L1MonsterInstance mob = iter.next();
        if (mob == null)
          continue; 
        if (mob.getMaxHp() <= 0)
          continue; 
        if (mob.isDead())
          continue; 
        if (mob.getNpcTemplate().get_digestitem() <= 0)
          continue; 
        if (mob.getDigestItemEmpty())
          continue; 
        checkDelItem(mob);
        Thread.sleep(50L);
      } 
    } catch (Exception e) {
      GeneralThreadPool.get().cancel(this._timer, false);
      NpcDigestItemTimer digestItemTimer = new NpcDigestItemTimer();
      digestItemTimer.start();
    } 
  }
  
  private void checkDelItem(L1MonsterInstance mob) {
    try {
      if (mob == null)
        return; 
      if (mob.isDead())
        return; 
      HashMap<L1ItemInstance, L1NpcInstance.DelItemTime> allItem = mob.getDigestItem();
      if (allItem.isEmpty())
        return; 
      int count = allItem.size();
      Iterator<L1ItemInstance> iter = allItem.keySet().iterator();
      while (iter.hasNext()) {
        L1ItemInstance key = iter.next();
        L1NpcInstance.DelItemTime value = allItem.get(key);
        if (value._del_item_time <= 0) {
          count--;
          continue;
        } 
        value._del_item_time -= 5;
        if (value._del_item_time > 0)
          continue; 
        mob.getInventory().removeItem(key, key.getCount());
      } 
      if (count <= 0)
        mob.getDigestItemClear(); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
